//
//  CorgiComposeViewController.swift
//  weibo
//
//  Created by Corgi on 17/3/28.
//  Copyright © 2017年 cocoaHangTou. All rights reserved.
//

import UIKit
import SVProgressHUD

class CorgiComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        setupNav()
        
        view.addSubview(composeTextView)
        
        view.addSubview(composeBottomView)
        
        composeTextView.addSubview(composePictureView)
        
        composeTextView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        composeBottomView.snp.makeConstraints { (make) in
            make.leading.bottom.trailing.equalToSuperview()
            make.height.equalTo(30)
        }
        
        composePictureView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.composeTextView)
            make.size.equalTo(CGSize(width: screenWidth - 20, height: screenWidth - 20))
            make.top.equalTo(self.composeTextView).offset(100)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonButtonClick), name: NSNotification.Name(rawValue: EMOTICONBUTTONCLICKNOTI), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonDeleteButtonClick), name: NSNotification.Name(rawValue: EMOTICONDELETEBUTTONCLICK), object: nil)
//
        composeBottomView.closure = { [weak self] (type) -> () in
        
            switch type {
            case .picture:
                print("图片")
                self?.selectImage()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("表情")
                self?.switchKeyboardView()
            case .add:
                print("+")
            }
        }
        
        composePictureView.closure = { [weak self] in
        
            self?.selectImage()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    fileprivate func setupNav() {
     
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imageName: nil, backImageName: nil, target: self, action: #selector(cancelAction))
        
        navigationItem.titleView = titleView
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBtn)
        
        navigationItem.rightBarButtonItem?.isEnabled = false
    }

    fileprivate lazy var titleView: UILabel = {
    
        let name = CorgiUserAccountViewModel.shared.account?.name ?? ""
        
        let text = "发微博" + "\n" + name
        
        let attrStr = NSMutableAttributedString(string: text)
        
        let range = (text as NSString).range(of: name)
        
        attrStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: THEMECOLOR], range: range)
    
        let lab = UILabel()
        
        lab.numberOfLines = 0
        
        lab.textAlignment = .center
        
        lab.attributedText = attrStr
        
        lab.sizeToFit()
        
        return lab
    }()
    
    fileprivate lazy var sendBtn: UIButton = {
    
        let btn = UIButton()
        
        btn.frame.size = CGSize(width: 50, height: 30)
        
        btn.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        
        btn.setTitle("发送", for: .normal)
    
        btn.titleLabel?.font = UIFont.systemFont(ofSize: FONTSIZEOFNORMAL)
        
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        
        btn.setTitleColor(UIColor.white, for: .normal)
        
        btn.setBackgroundImage(UIImage(named:"common_button_orange"), for: .normal)
        
        btn.setBackgroundImage(UIImage(named:"common_button_white_disable"), for: .disabled)
        
        btn.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: .highlighted)
        
        return btn
    }()
    
    fileprivate lazy var composeTextView: CorgiComposeTextView = {
    
        let Txtview = CorgiComposeTextView()
        
        Txtview.delegate = self
        
        Txtview.alwaysBounceVertical = true
    
        Txtview.placeholder = "这是自定义textView的placeholderLabel"
        
        Txtview.font = UIFont.systemFont(ofSize: 16)
        
        return Txtview
    }()
    
    fileprivate lazy var composeBottomView: CorgiComposeBottomView = CorgiComposeBottomView()

    fileprivate lazy var composePictureView: CorgiComposeCollectionView = CorgiComposeCollectionView()
    
    fileprivate lazy var emoticonKeyboardView: CorgiEmoticonKeyboardView = {
    
        let view = CorgiEmoticonKeyboardView()
    
        view.frame.size = CGSize(width: screenWidth, height: 216)
        
        return view
    }()
    
    deinit {
    
        NotificationCenter.default.removeObserver(self)
    }
}

extension CorgiComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    fileprivate func switchKeyboardView() {
        
        composeTextView.inputView = (composeTextView.inputView == nil) ? emoticonKeyboardView : nil
        
        composeBottomView.isEmoticon = (composeTextView.inputView != nil)

        composeTextView.reloadInputViews()
        
        composeTextView.becomeFirstResponder()
    }
    
    fileprivate func selectImage() {
        
        let pickerVC = UIImagePickerController()
        
        pickerVC.delegate = self
        
        self.present(pickerVC, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        picker.dismiss(animated: true, completion: nil)
        
        guard let img = info["UIImagePickerControllerOriginalImage"] as? UIImage else {
        
            return
        }
        
        let dealedImg = img.dealImageScale(maxWidth: 400)
        
        composePictureView.addImage(img: dealedImg)
    }
}

extension CorgiComposeViewController {

    @objc fileprivate func keyboardWillChangeFrame(noti: NSNotification) {
       
        guard let userInfo = noti.userInfo else {
            
            return
        }
        
        let frame = (userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        
        self.composeBottomView.snp.updateConstraints { (make) in
            
            make.bottom.equalToSuperview().offset(frame.origin.y - screenHeight)
        }
        
        let duration = (userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        
        UIView.animate(withDuration: duration) {
            
            self.view.layoutIfNeeded()
        }
    }
    
    @objc fileprivate func emoticonDeleteButtonClick() {
        composeTextView.deleteBackward()
    }
    
    @objc fileprivate func emoticonButtonClick(noti: Notification) {
        
        guard let emoticonModel = noti.object as? CorgiEmoticonModel else {
            
            return
        }
        
        CorgiEmoticonTools.shared.saveRecentModel(model: emoticonModel)
        
        emoticonKeyboardView.reloadPageViewData()
        
        if emoticonModel.isEmoji {
        
            let code = ((emoticonModel.code ?? "") as NSString).emoji() ?? ""
        
            composeTextView.insertText(code)
            
        } else {
        
            let allAttributedText = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            
            let allPath = emoticonModel.allPath ?? ""
            
            let image = UIImage(named: allPath, in: CorgiEmoticonTools.shared.emoticonsBundle, compatibleWith: nil)
            
            let lineHeight = composeTextView.font!.lineHeight
            
            let att = CorgiTextAttachment()
            
            att.model = emoticonModel
            
            att.image = image
            
            att.bounds = CGRect(x: 0, y: 0, width: lineHeight, height: lineHeight)
            
            let attr = NSAttributedString(attachment: att)
            
            let selectedRange = composeTextView.selectedRange
            
            allAttributedText.replaceCharacters(in: selectedRange, with: attr)
            
            allAttributedText.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 0, length: allAttributedText.length))
            
            composeTextView.attributedText = allAttributedText
            
            composeTextView.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
            
            NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: nil)
            
            composeTextView.delegate?.textViewDidChange?(composeTextView)
        }
    }
}

extension CorgiComposeViewController: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
     
        navigationItem.rightBarButtonItem?.isEnabled = composeTextView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        self.composeTextView.resignFirstResponder()
    }
}

extension CorgiComposeViewController {

    @objc fileprivate func cancelAction() {
        
        composeTextView.resignFirstResponder()
        
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func sendAction() {
        
        var allText = ""
        
        composeTextView.attributedText.enumerateAttributes(in: NSRange(location: 0, length: composeTextView.attributedText.length), options: []) { (dict, range, _) in
            
            if let att = dict["NSAttachment"] as? CorgiTextAttachment {
            
                allText += (att.model?.chs ?? "")
                
            } else {
            
                allText += composeTextView.attributedText.attributedSubstring(from: range).string
            }
        }
        
        self.composePictureView.imageList.count > 0 ? upload(status: allText) : update(status: allText)
    }
}

extension CorgiComposeViewController {

    fileprivate func update(status: String) {
        
        HMNetworkTools.shared.composeUpdate(status: status) { (result, error) in
            
            if error != nil {
            
                SVProgressHUD.showError(withStatus: "发送失败")
            } else {
            
                SVProgressHUD.showSuccess(withStatus: "发送成功")
            }
            
            self.cancelAction()
        }
    }
    
    func upload(status: String) {
        
        HMNetworkTools.shared.composeUpload(status: status, imageList: self.composePictureView.imageList) { (response, error) in
         
            if error != nil {
                
                SVProgressHUD.showError(withStatus: "发送失败")
            } else {
                
                SVProgressHUD.showSuccess(withStatus: "发送成功")
            }
            
            self.cancelAction()
        }
    }
}
